--[[
FilePath: \Lua\View\UITotalRecharge\UITotalRechargeShow.lua
累充活动
--]]

require 'View/UIBase/UIBase'

UITotalRechargeShow = UIBase.New(PanelNames.UITotalRechargeShow)
local _M = UITotalRechargeShow
local MonthCardID=10101
local ChargeType=
{
    totalCharge=1,
    dailyCharge=2,
    layerdCharge =3
}
_M.hasInit = false
_M.activeId = nil
_M.playEffect = false
function _M.Init(func, id)
    _M.activeId = id
    local activeTable = logicMgr.ActiveManager.getActiveTableList(id);
    local type = tonumber(activeTable.f_ActivityType)
    _M.chargeType =ChargeType.totalCharge
    if type==14 then
        _M.chargeType =ChargeType.totalCharge
    elseif type==18 then
        _M.chargeType =ChargeType.dailyCharge
        _M.dailyModelTable=G.dataTable[activeTable.f_ModelName]
    elseif type==23 then
        _M.chargeType =ChargeType.layerdCharge
        _M.dailyModelTable=G.dataTable[activeTable.f_ModelName]
    end

    UIBase.Init(_M, func)
end
function _M:InitPet()
    local genes=decodeJsonStrToTabel(self.dailyModelTable[tostring(self.activeId)].f_elves)
    self:showPetModel(genes)
end
function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnClose)
        self.tipTime = self:GetChild("tipTime");
        self.tipEndDecs = self:GetChild("tipDecs2");
        self.name = self:GetChild("title");
        self.activityTitle = self:GetChild("activitytitle");
        self.itemList = self:GetChild("List");
        self.isOver = self:GetController("isover");
        self.CoinLb = self:GetChild("ResBar");
        self.typeController=self:GetController("Type")
        self.bannerText=self:GetChild("bannerTime")
        self.coin=self:GetChild("ResBar")
        self.Model_Pet = self:GetChild("lihui")
        self.rewardCtrl = self:GetChild("Reward"):GetController("Type")
        self.bannerBg = self:GetChild("bannerBg");
        self.heroBg = self:GetChild("bg");
        self.nameBg = self:GetChild("name");

        local activeListTableData = G.dataTable["t_activitylist"];
        --self.modelData = G.dataTable[activeListTableData[tostring(self.activeId)].f_ModelName][tostring(self.activeId)];
        --self.itemConfig = G.dataTable[tostring(self.modelData.f_ItemTableName)];
        self.itemList:SetVirtual()
        self.itemList.itemRenderer = self.RefreshItem;
        self:addEvent()
        self:InitView()
        if self.chargeType==ChargeType.dailyCharge or self.chargeType==ChargeType.layerdCharge then
            self:InitPet()
        end
        _M.hasInit = true
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.RefreshActive);
    self:RegisterOnClick(self:GetChild("help"),self.onClickBtnHelp)
    self:RegisterOnClick(self:GetChild("Reward"),self.onClickBtnReward)
end
function _M:onClickBtnHelp()
    --self.dailyModelTable[tostring(self.activeId)].f_elves
    local modelData=self.dailyModelTable[tostring(self.activeId)]
    logicMgr.UIShowManager.ShowCommonTips(modelData.f_ExplainTitle, modelData.f_ExplainText);
end
function _M:onClickBtnReward()
    if self.rewardCtrl.selectedIndex == 1 then
        local todayIndex = self.serverData.curPeriodDays
        local config = _M.serverData.itemData[todayIndex]
        ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, config.f_ItemId, todayIndex, 1})
    elseif self.rewardCtrl.selectedIndex == 0 then
        --_M.ClickGoto();
        local awardItem = decodeJsonStrToTabel(G.dataTable["t_global"]["533"]["f_string_value"])
        local awardItemId = tonumber(awardItem[1][1]) or 1
        showUI(PanelNames.UIBagItemInfo, { itemModelId = awardItemId });
    end
end
function _M:removeEvent()

end

function _M.ClickGoto(id)
    --closeUI(_M._panelName);
    logicMgr.HeroManager.setGetNewHeroShow();
    closeUI(PanelNames.UITotalRecharge);
    closeUI(PanelNames.UIActivity);
    showUI(PanelNames.UIHeadMenu);
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Cost, true) then
        logicMgr.CostManager.gotoCostById(id);
    end
end

function _M:InitView()
    if self.activeId == nil then
        self:OnBack();
    else
        if _M.chargeType==ChargeType.totalCharge then
            self.name.text = getLanguage("ActivityDesc1080101");
            self.typeController.selectedIndex=0;
        elseif _M.chargeType==ChargeType.dailyCharge then
            self.activityTitle.text=getLanguage("ActivityDesc1100303")
            self.typeController.selectedIndex=1;
        elseif _M.chargeType==ChargeType.layerdCharge then
            self.activityTitle.text=getLanguage("ActivityDesc1400104")
            self.typeController.selectedIndex=2;
        end
    end
end

function _M:RefreshActive()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
        self:RefreshView();
        local time = HelperFunc.GetServerTime();
        self.endCountDown=self.serverData.endTime - time
        self:updateActiveCountDown();
        self:TimeCall(self.updateActiveCountDown, 1000, -1);
    end
end

function _M:RefreshView()
    local serverItemData = self.serverData.itemData
    local itemNum = #serverItemData
    self.itemList.numItems = itemNum
    if self.playEffect then
        self.playEffect = false;
        HelperFunc.ListTranstionPlay(self.itemList);
    end
    if self.chargeType==ChargeType.dailyCharge then
        self.bannerText.text=string.format(getLanguage("ActivityDesc1100401"),self:HasAcceptNum(),itemNum)
    elseif self.chargeType==ChargeType.layerdCharge then
        local todayIndex = self.serverData.curPeriodDays
        if self.serverData.rewardedSet[todayIndex] then
            if self.serverData.rewardedSet[todayIndex].extraStatus == 1 then  --可领取
                self.rewardCtrl.selectedIndex = 1
            elseif self.serverData.rewardedSet[todayIndex].extraStatus == 2 then  --已领取
                self.rewardCtrl.selectedIndex = 2
            else
                self.rewardCtrl.selectedIndex = 0   --充了不足六块
            end
        else    --今天没有充值数据，没充钱
            self.rewardCtrl.selectedIndex = 0
        end
    else
        if self.tableData.f_TitlePic ~= nil and self.tableData.f_TitlePic ~= "" then
            self.heroBg.url = tostring(self.tableData.f_TitlePic);
        else
            self.heroBg.visible = false;
        end
        if self.tableData.f_Tips ~= nil and self.tableData.f_Tips ~= "" then
            self.nameBg.url = tostring(self.tableData.f_Tips);
        else
            self.nameBg.visible = false;
        end
        if self.tableData.f_Banner ~= nil and self.tableData.f_Banner ~= "" then
            self.bannerBg.url = tostring(self.tableData.f_Banner);
        else
            self.bannerBg.visible = false;
        end
    end
    for i = 1, itemNum do
        local config = _M.serverData.itemData[i];
        if config ~= nil then
            local buyCountData
            if _M.serverData.rewardedSet ~= nil then
                buyCountData = _M.serverData.rewardedSet[tostring(config.f_ItemId)];
            end
            if  self.chargeType==ChargeType.totalCharge then
                if buyCountData == nil or (not buyCountData.rewarded) then
                    if _M.serverData.num >= tonumber(config.f_Price) then
                        self.itemList:ScrollToView(i - 1, true, true);
                        break;
                    end
                end
            elseif self.chargeType==ChargeType.dailyCharge then
                local index=1
                for _,v in ipairs(serverItemData )do
                    local rewardData= self.serverData.rewardedSet[v.f_ItemId]
                    local flag1=rewardData~=nil and rewardData.state==2
                    if flag1 then
                        index=index+1
                    else
                        break
                    end
                end
                index=index-1
                index=Mathf.Clamp(index,0,self.itemList.numItems-1)
                self.itemList:ScrollToView(index, true, true);
            end
        end
    end
    self.isGet = false;
    self:RefreshCoin()
end
function _M:RefreshCoin()
    self.coin:GetChild("icon").icon = "ui://ItemAtlas/"..CurrencyEnum.GOLD;
    self.coin:GetChild("title").text = logicMgr.ItemManager.getCurrencyCountByModelId(1);
end
function _M:HasAcceptNum()
    local num=0
    for i,v in pairs(self.serverData.rewardedSet)do
        if v.state==1 or v.state==2 then
            num=num+1
        end
    end
    return num
end
function _M.RefreshItem(index, itemObj)
    local itemList = itemObj:GetChild("itemList");
    local title = itemObj:GetChild("title");


    local btn_Get = itemObj:GetChild("btn_Get");
    btn_Get.onClick:Clear();
    local status = itemObj:GetController("status");
    local typeCtrl=itemObj:GetController("Type")
    local tips=itemObj:GetChild("Tips")
    local payBar=itemObj:GetChild("n10")
    local lanStr=
    {
        [1]=getLanguage("Sys_tips2"),
        [2]=getLanguage("ActivityDesc1100301"),
        [3]=getLanguage("ActivityDesc1100304"),
    }
    local btn_Go = itemObj:GetChild("btn_Go");
    btn_Go.onClick:Clear();
    if _M.chargeType==ChargeType.dailyCharge then
        typeCtrl.selectedIndex=1
        title.text=string.format(lanStr[2],tostring(index+1))
        btn_Go.onClick:Add(function()
            _M.ClickGoto(MonthCardID);
        end);
    elseif _M.chargeType==ChargeType.layerdCharge then
        typeCtrl.selectedIndex=2
        btn_Go.onClick:Add(function()
            _M.ClickGoto(MonthCardID);
        end);
    else
        typeCtrl.selectedIndex=0
        btn_Go.onClick:Add(function()
            _M.ClickGoto();
        end);
    end
    local config = _M.serverData.itemData[index + 1];
    local function SetDesc(p1,p2,num,max)
        if _M.chargeType==ChargeType.totalCharge then
            title.text = string.format(lanStr[1],p1,p2)
        elseif _M.chargeType==ChargeType.dailyCharge then
            tips.text=string.format(lanStr[3],p1,p2)
            payBar.min=0
            payBar.max=max
            payBar.value=num
        elseif _M.chargeType==ChargeType.layerdCharge then
            tips.text=string.format(lanStr[3],p1,p2)
            payBar.min=0
            payBar.max=max
            payBar.value=num
        end
    end
    if _M.chargeType==ChargeType.totalCharge then
        if config == nil then
            status.selectedIndex = 2;
            SetDesc(_M.serverData.num, _M.serverData.num)
        else
            local reward = decodeJsonStrToTabel(config.f_Award);
            logicMgr.CostManager.RefreshItemList(itemList, reward);
            local buyCountData
            if _M.serverData.rewardedSet ~= nil then
                buyCountData  = _M.serverData.rewardedSet[tostring(config.f_ItemId)];
            end
            if buyCountData ~= nil and buyCountData.rewarded then
                status.selectedIndex = 2;
                SetDesc( config.f_Price,config.f_Price)
            else
                if _M.serverData.num >= tonumber(config.f_Price)then
                    status.selectedIndex = 1;
                    SetDesc(("[color=#A0C776]"..config.f_Price.."[/color]"), config.f_Price)
                    btn_Get.onClick:Add(function()
                        --if _M.isGet then
                        --    return;
                        --end
                        _M.isGet = true;
                        ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, config.f_ItemId});
                    end);
                else
                    status.selectedIndex = 0;
                    SetDesc(("[color=#FF2A4D]".._M.serverData.num.."[/color]"), config.f_Price)
                end
            end
        end
    elseif _M.chargeType==ChargeType.dailyCharge then
        local reward = decodeJsonStrToTabel(config.f_Award);
        logicMgr.CostManager.RefreshItemList(itemList, reward);
        local  rewardData = _M.serverData.rewardedSet[(config.f_ItemId)];
        if rewardData~=nil and rewardData.state==2 then
            status.selectedIndex = 2;
            SetDesc(config.f_Price,config.f_Price,config.f_Price,config.f_Price)
        elseif rewardData~=nil and rewardData.state==1 then
            status.selectedIndex = 1;
            SetDesc(("[color=#A0C776]"..config.f_Price.."[/color]"), config.f_Price,config.f_Price,config.f_Price)
            btn_Get.onClick:Add(function()
                --if _M.isGet then
                --    return;
                --end
                _M.isGet = true;
                ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, config.f_ItemId});
            end);
        else
            local flag=_M.serverData.todayID==-1 and index+1==1
            if config.f_ItemId==_M.serverData.todayID or flag then
                status.selectedIndex = 0;
                SetDesc(("[color=#FF2A4D]".._M.serverData.todayPay.."[/color]"), config.f_Price,_M.serverData.todayPay,config.f_Price)
            else
                status.selectedIndex=3
                SetDesc(("[color=#FF2A4D]"..(0).."[/color]"), config.f_Price,0,config.f_Price)
            end
        end
    elseif _M.chargeType == ChargeType.layerdCharge then
        local reward = config.f_Award;
        logicMgr.CostManager.RefreshItemList(itemList, reward);
        local rewardData = _M.serverData.rewardedSet[index+1];
        if rewardData~=nil and rewardData.state==2 then --已领取
            status.selectedIndex = 2;
            title.text = string.format(getLanguage("ActivityDesc1400101"),tostring(index+1),tostring(config.f_Price))
        elseif rewardData~=nil and rewardData.state==1 then --可领取
            status.selectedIndex = 1;
            title.text = string.format(getLanguage("ActivityDesc1400101"),tostring(index+1),tostring(config.f_Price))
            SetDesc(("[color=#A0C776]"..config.f_Price.."[/color]"), config.f_Price,config.f_Price,config.f_Price)
            btn_Get.onClick:Add(function()
                _M.isGet = true;
                ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, config.f_ItemId, index+1, 0});
            end);
        else
            local dayIndex = _M.serverData.curPeriodDays
            if index+1 <= dayIndex then
                status.selectedIndex = 0;   --前往
                local payNum = 0
                if _M.serverData.rewardedSet[index+1] then
                    payNum = _M.serverData.rewardedSet[index+1].payNum or 0
                end
                SetDesc(("[color=#FF2A4D]"..payNum.."[/color]"), config.f_Price,payNum,config.f_Price)
                if index+1 ==  _M.serverData.borderIndex then
                    title.text = string.format(getLanguage("ActivityDesc1400102"),tostring(index+1),tostring(config.f_Price - payNum))
                else
                    status.selectedIndex = 4;
                    title.text = string.format(getLanguage("ActivityDesc1400103"),tostring(index+1),tostring(_M.serverData.borderIndex))
                end
            else
                status.selectedIndex = 3    --未解锁
                title.text = string.format(getLanguage("ActivityDesc1400101"),tostring(index+1),tostring(config.f_Price))
            end
        end
    end
end
function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    if self.endCountDown <= 0 then
        self.isOver.selectedIndex = 1;
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        self.isOver.selectedIndex=0
        self.tipTime.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M:showPetModel(genes)
    if #genes == PetManager.PetPart.Ornament then
        local _petModelInfo = {}
        _petModelInfo.parentGO = self.Model_Pet
        if self.PetModelGO and self.goWrapper then
            _petModelInfo.modelGO = self.PetModelGO
            _petModelInfo.modelWrapper = self.goWrapper
            PetManager.PetModelRefresh(_petModelInfo,genes,true)
        else
            self:removePetModel()
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab,function(go)
                self.PetModelGO = newObject(go)

                local com = self.PetModelGO:GetComponent("SkeletonGraphic")

                if self.PetModelGO and com then
                    com.material = resMgr.Pet_Copy_Mat
                    com.material:SetFloat("_StencilComp",8)
                    com.material:SetFloat("_Stencil",1);
                end

                _petModelInfo.modelGO = self.PetModelGO
                local _modelWrapper = self.goWrapper
                self.goWrapper = GoWrapper.New()
                _petModelInfo.modelWrapper = self.goWrapper
                PetManager.PetModelFirstSet(_petModelInfo,genes,true,Vector3.New(0,0,0),Vector3.New(3,3,1))
                if _modelWrapper then
                    _modelWrapper:Dispose()
                end
            end)
        end
    end
end
function _M:removePetModel()
    if self.PetModelGO then
        destroy(self.PetModelGO)
    end
    self.PetModelGO = nil
end
-- 显示
function _M:OnEnable()
    self.playEffect = true;
    logicMgr.HeroManager.setGetNewHeroShow(true);
    self:RefreshActive();
end

function _M:OnClose()
    logicMgr.HeroManager.setGetNewHeroShow();
    self:OnBack();
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    _M.hasInit = false
    _M.activeId = nil
    _M.playEffect = false
end

return _M;